package com.luyuan.crm.sale.mapping;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.SessionImplementor;
import org.hibernate.id.Configurable;
import org.hibernate.id.IdentifierGenerator;
import org.hibernate.type.Type;

import com.luyuan.crm.sale.model.Order;
import com.luyuan.crm.sale.model.OrderType;

public class OrderIdentifierGenerator implements IdentifierGenerator, Configurable {

    private final static int COUNT = 1000;

    private SimpleDateFormat format;

    @Override
    public void configure(Type type, Properties params, Dialect d) throws MappingException {
        format = new SimpleDateFormat(params.getProperty("dateFormat", "yyyyMMddHHmmssSS"));
    }

    @Override
    public Serializable generate(SessionImplementor session, Object object) throws HibernateException {
        String id = null;
        id = format.format(new Date()) + String.valueOf(Math.round(Math.random() * COUNT));

        Order order = (Order) object;

        if (order.getOrderType() == OrderType.FORMULA) {
            id = "F" + id;
        }
        else if (order.getOrderType() == OrderType.SINGLE_PRODUCT) {
            id = "S" + id;
        }

        return id;
    }
}
